package com.ybkj.daijia.server.event.listener;

import com.ybkj.daijia.Setting;
import com.ybkj.daijia.serverUtils.SettingUtils;
import com.ybkj.daijia.server.OrderRevokeTimerTask;
import com.ybkj.daijia.server.OrderTimerTask;
import com.ybkj.daijia.server.event.model.OrderCreateEvent;
import com.ybkj.daijia.server.model.Company;
import com.ybkj.daijia.server.model.Order;
import com.ybkj.daijia.server.scheduler.ThreadControl;
import com.ybkj.daijia.server.service.CompanyService;
import com.ybkj.daijia.server.websocket.WebSocketSend;
import java.util.Date;
import java.util.Timer;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ApplicationEventMulticaster;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

@Component
public class OrderCreateEventListener implements ApplicationListener<OrderCreateEvent> {

    private static final Logger logger = LoggerFactory.getLogger(OrderCreateEventListener.class);

    @Autowired
    private CompanyService companyService;

    @Autowired
    private SettingUtils settingUtils;

    @Autowired
    private ApplicationEventMulticaster applicationEventMulticaster;

    @Override
    @Async
    public void onApplicationEvent(OrderCreateEvent event) {

        Order order = (Order) event.getSource();

        logger.debug("order created event:{}", order.getOrderNumber());

        //推送数据到浏览器
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("clientName", order.getClientName());
        jsonObject.put("orderCarType", order.getOrderCarType());
        jsonObject.put("orderMemo", order.getMemo());
        jsonObject.put("orderID", order.getId());
        jsonObject.put("orderNumber", order.getOrderNumber());
        jsonObject.put("bookAddress", order.getFromPlace());
        jsonObject.put("bookTime", DateFormatUtils.format(order.getServerTime(), "HH:mm"));
        jsonObject.put("lat", order.getClientLatitude());
        jsonObject.put("lng", order.getClientLongitude());
        jsonObject.put("type", "newOrders");
        Company mainCompany = companyService.getMain();
        WebSocketSend.boardcastToCompany(jsonObject, order.getCompanyId(), mainCompany.getId());

        //自动派单定时器
        if (ThreadControl.SysAutoRunning) {
            Setting setting = settingUtils.get();

            Timer timer = new Timer();
            OrderTimerTask orderTimerTask = new OrderTimerTask(
                setting.getAutoPaidanKm1(), setting.getAutoPaidanTime1(),
                setting.getAutoPaidanKm2(), setting.getAutoPaidanTime2(),
                setting.getAutoPaidanKm3(), setting.getAutoPaidanTime3(),
                applicationEventMulticaster,
                order.getId(), order.getClientLatitude(), order.getClientLongitude(), 1
            );

            Integer howLong = setting.getAutoPaidanTime1();
            if (order.getServerTime().getTime() - System.currentTimeMillis() > 1000 * 60 * 30) {
                howLong =
                    (int) (order.getServerTime().getTime() - System.currentTimeMillis() - 1000 * 60 * 30)
                        / 1000;
            }

            timer.schedule(orderTimerTask, howLong * 1000);
            ThreadControl.TaskMaps.put("task_" + order.getId(), timer);
            //自动收回
            if (setting.getRevokeTime() != 0) {
                try {
                    logger.debug("创建订单回收订单定时器激活");
                    OrderRevokeTimerTask orderRevokeTimerTask = new OrderRevokeTimerTask(
                        order.getId(), "daijia", applicationEventMulticaster);
                    Integer howLongs = setting.getRevokeTime();
                    timer.schedule(orderRevokeTimerTask, howLongs * 60 * 1000);
                } catch (Exception e1) {
                    e1.printStackTrace();
                }
            }
        }

    }

}
